/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package easemob.chatuidemo.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMCursorResult;
import com.easemob.chat.EMGroupInfo;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseNormalActivity;
import com.wolfalpha.utron.view.XListView;

import java.util.ArrayList;
import java.util.List;


/**
 * 公开群
 */
public class PublicGroupsActivity extends BaseNormalActivity implements XListView.IXListViewListener {
    private XListView listView;
    private GroupsAdapter adapter;

    private List<EMGroupInfo> groupsList;
    private boolean isFirstLoading = true;
    private boolean hasMoreData = true;
    private String cursor = "1";        //取第一页
    private boolean isLoading;
    private final int pagesize = 1;
//    private Button searchBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_partner_public_groups);

        setTvTitle("公开项目群");

        listView = (XListView) findViewById(R.id.partner_public_group_list);
        listView.setPullLoadEnable(true);
        listView.setXListViewListener(this);
        groupsList = new ArrayList<EMGroupInfo>();
//        searchBtn = (Button) findViewById(R.id.btn_search);

        //获取及显示数据
        loadAndShowData();

        //设置item点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startActivity(new Intent(PublicGroupsActivity.this, GroupSimpleDetailActivity.class).
                        putExtra("groupinfo", adapter.getItem(position - 1)));
            }
        });
    }

    /**
     * 搜索
     */
    public void search() {
//        startActivity(new Intent(this, PublicGroupsSeachActivity.class));
    }


    private void loadAndShowData() {
        new Thread(new Runnable() {

            public void run() {
                try {
                    if (TextUtils.isEmpty(cursor)) return;
                    isLoading = true;
                    final EMCursorResult<EMGroupInfo> result = EMGroupManager.getInstance().getPublicGroupsFromServer(pagesize, cursor);
                    //获取group list
                    final List<EMGroupInfo> returnGroups = result.getData();
                    runOnUiThread(new Runnable() {

                        public void run() {
//                            searchBtn.setVisibility(View.VISIBLE);
                            groupsList.addAll(returnGroups);
                            if (returnGroups.size() != 0) {
                                //获取cursor
                                cursor = result.getCursor();
                            }
                            if (isFirstLoading) {
                                isFirstLoading = false;
                                //设置adapter
                                adapter = new GroupsAdapter(PublicGroupsActivity.this, 1, groupsList);
                                listView.setAdapter(adapter);
                            } else {
                                if (returnGroups.size() < pagesize) {
                                    hasMoreData = false;
                                }
                                adapter.notifyDataSetChanged();
                            }
                        }
                    });
                } catch (EaseMobException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(PublicGroupsActivity.this, "加载数据失败，请检查网络或稍后重试", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                isLoading = false;
            }
        }).start();
    }

    @Override
    public void onRefresh() {
        listView.stopRefresh();
    }

    @Override
    public void onLoadMore() {
        if (listView.getCount() != 0) {
            int lasPos = listView.getLastVisiblePosition();
            if (hasMoreData && !isLoading && lasPos == listView.getCount() - 1) {
                loadAndShowData();
            }
        }
        listView.stopLoadMore();
    }

    /**
     * adapter
     */
    private class GroupsAdapter extends ArrayAdapter<EMGroupInfo> {

        private LayoutInflater inflater;

        public GroupsAdapter(Context context, int res, List<EMGroupInfo> groups) {
            super(context, res, groups);
            this.inflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.row_group, null);
            }

            ((TextView) convertView.findViewById(R.id.name)).setText(getItem(position).getGroupName());
            return convertView;
        }
    }

    public void back(View view) {
        finish();
    }
}
